package com.yuanduo_app.bridge;

import android.content.Intent;

import com.baozi.Zxing.CaptureActivity;
import com.baozi.Zxing.ZXingConstants;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactMethod;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.xujl.fastlib.base.BaseActivity;
import com.xujl.fastlib.base.BaseModule;
import com.xujl.fastlib.utils.AppManager;
import com.xujl.fastlib.utils.ToastUtils;
import com.xujl.task.RxExecutor;
import com.xujl.task.Task;

import com.yuanduo_app.MainActivityControl;
import com.yuanduo_app.consts.PermissionGroup;
import com.yuanduo_app.consts.RNEvent;
import com.yuanduo_app.manager.RNModuleManager;

import androidx.annotation.NonNull;

/**
 * 二维码扫描
 */
public class QrCodeModule extends BaseModule {
    public static final int REQUEST_CODE = 85;

    public QrCodeModule (ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @NonNull
    @Override
    public String getName () {
        return "QrCodeModule";
    }


    @ReactMethod
    public void qrCodeScan () {
        RxExecutor.getInstance()
                .executeUiTask(new Task() {
                    @Override
                    public void onlyRunUiTask () {
                        super.onlyRunUiTask();
                        final BaseActivity activity = AppManager.getAppManager().findActivity(MainActivityControl.class);
                        RxPermissions rxPermissions = new RxPermissions(activity);
                        rxPermissions.request(PermissionGroup.QR_CODE)
                                .subscribe(aBoolean  -> {
                                    if (aBoolean) {
                                        Intent intent = new Intent();
                                        intent.setClass(activity, CaptureActivity.class);
                                        activity.startActivityForResult(intent, REQUEST_CODE);
                                    } else {
                                        ToastUtils.toast("没有权限访问相机！");
                                    }
                                });
                    }
                });

    }

    public static void onActivityResult (int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && data != null) {
            String qrResult = data.getStringExtra(ZXingConstants.ScanResult);
            QrCodeModule module = RNModuleManager.getInstance().getModule(QrCodeModule.class);
            if (module != null) {
                module.sendEvent(RNEvent.QR_CODE_RESULT, qrResult);
            }
        }
    }

}
